package com.htzos.main.ctrl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.htzos.admin.ac.bean.AcMessageBase;
import com.htzos.admin.ac.bean.AcMsgreadlogBase;
import com.htzos.admin.ac.bean.AcNoticeBase;
import com.htzos.admin.ac.service.AcMessageBaseService;
import com.htzos.admin.ac.service.AcMsgreadlogBaseService;
import com.htzos.admin.ac.service.AcNoticeBaseService;
import com.htzos.admin.system.bean.MenuTree;
import com.htzos.admin.system.bean.SystemRoleMenu;
import com.htzos.admin.system.bean.SystemUserBase;
import com.htzos.admin.system.service.SystemRoleBaseService;
import com.htzos.admin.system.service.SystemRoleMenuService;
import com.htzos.admin.system.service.SystemUserBaseService;
import com.htzos.base.parent.ctrl.BaseController;
import com.htzos.common.tool.ExtQueryBean;
import com.htzos.common.tool.TldTool;
import com.htzos.common.util.CommonUtil;
import com.htzos.main.tool.LoginTool;
/**
 * 主控制器  管理 一些主要的访问  如登录页 、首页、注册页 等单页面的跳转
 *
 * @author xudz
 * @time 2017 2017年1月5日 上午10:05:51
 */
@Controller
@RequestMapping("")
public class MainController extends BaseController{
	
	@Resource
	private SystemUserBaseService systemUserBaseService;
	@Resource
	private SystemRoleBaseService systemRoleBaseService;
	@Resource
	private SystemRoleMenuService systemRoleMenuService;
	@Resource
	private AcMessageBaseService acMessageBaseService;
	@Resource
	private AcNoticeBaseService acNoticeBaseService;
	@Resource
	private AcMsgreadlogBaseService acMsgreadlogBaseService;
	
	
	Logger logger=Logger.getLogger(this.getClass());

	/**
	 * 跳转到首页
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 上午10:23:28
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
		logger.info("调用前往管理首页");
		
		SystemUserBase user = (SystemUserBase) request.getSession().getAttribute(CommonUtil.CURRENTUSER);
		List<SystemRoleMenu> menuList = systemRoleMenuService.systemRoleMenuListByUser(user.getId());
		List<MenuTree> menuTrees=LoginTool.getMenuTree(menuList);
		
		return new ModelAndView("admin/index").addObject("menuTrees", menuTrees);
	}
	
	
	/**
	 * 后台欢迎页获取信息
	 *
	 * @author xudz
	 * @time 2017 2017年2月10日 下午4:26:16
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/welcome")
	public ModelAndView welcome(HttpServletRequest request,HttpServletResponse response){
		Properties props = System.getProperties();
		ModelAndView mv=new ModelAndView("admin/welcome");
		String ipAddress = null;
	     //ipAddress = request.getRemoteAddr();
	    ipAddress = request.getHeader("x-forwarded-for");
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	      ipAddress = request.getHeader("Proxy-Client-IP");
	    }
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	      ipAddress = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
		  ipAddress = request.getRemoteAddr();
		  if(ipAddress.equals("127.0.0.1")){
		       //根据网卡取本机配置的IP
		    InetAddress inet=null;
		    try {
			    	inet = InetAddress.getLocalHost();
		    } catch (UnknownHostException e) {
			     e.printStackTrace();
			}
			ipAddress= inet.getHostAddress();
		  }
	         
	   }
	
	     //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
	     if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
	         if(ipAddress.indexOf(",")>0){
	             ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
	         }
	     }
		
	    mv.addObject("ip", ipAddress);
	    mv.addObject("logincount",9999);
	    mv.addObject("lastLoginIP","作者懒未查询日志");
	    mv.addObject("lastLogin","作者懒，未查询日志");
		mv.addObject("os", props.getProperty("os.name"));
		mv.addObject("java_version", props.getProperty("java.version"));
		mv.addObject("database_version", "1.0.1");
		mv.addObject("web_server_version", request.getSession(false).getServletContext().getServerInfo());
		
		
		return mv;
	}
	
	/**
	 * 跳转到登录页面
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 上午11:05:27
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toLogin")
	public ModelAndView toLogin(HttpServletRequest request,HttpServletResponse response){
		//如果已经登录调到后台首页
		HttpSession session = request.getSession();
		if(session.getAttribute(CommonUtil.CURRENTUSER)!=null){
			return new ModelAndView("redirect:/index");
		}
		logger.info("调用前往登录页");
		return new ModelAndView("login");
	}
	
	/**
	 * 登录操作
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 下午12:09:04
	 * @parameter 
	 * @param request
	 * @param systemUserBase
	 * @param extQuery
	 * @return
	 */
	@RequestMapping("/doLogin")
	public ModelAndView login(HttpServletRequest request,
			SystemUserBase systemUserBase, ExtQueryBean extQuery) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("passwordEncrypt");
		logger.info(userName + ",用户登录。");

		if(password == null || password.isEmpty()||userName==null||userName.isEmpty()){
			logger.info(userName + ",登录失败。");
			request.setAttribute("loginMessage", "用户名者密码不能为空！");
			return new ModelAndView("login");
		}
		String md5PassWord = password;//Md5.getMd5(password);
		SystemUserBase user = new SystemUserBase();
		user.setAccount(userName);
		user.setPassword(md5PassWord);
		user.setActiveFlag(1);
		List<SystemUserBase> list = systemUserBaseService.systemUserBaseList(user, null);
		if (list.size() > 0) {
			logger.info(userName + ",登录成功。");
			user = list.get(0);

			HttpSession session = request.getSession();
			session.setAttribute(CommonUtil.CURRENTUSER, user);
			
			// 获取当前用户权限可访问的功能树
			List<SystemRoleMenu> menuList = systemRoleMenuService.systemRoleMenuListByUser(user.getId());
			LoginTool.initRole(session, menuList);

			return new ModelAndView("redirect:/index");
		} else {
			logger.info(userName + ",登录失败。");
			request.setAttribute("loginMessage", "用户名或者密码错误！");
			return new ModelAndView("login");
		}

	}
	
	/**
	 * 登出
	 *
	 * @author xudz
	 * @time 2017 2017年1月6日 上午9:56:17
	 * @parameter 
	 * @param request
	 * @param systemUserBase
	 * @param extQuery
	 * @return
	 */
	@RequestMapping("/loginout")    
    public ModelAndView lonout(HttpServletRequest request,SystemUserBase systemUserBase, ExtQueryBean extQuery) {
		request.getSession().removeAttribute(CommonUtil.CURRENTUSER);
		request.getSession().removeAttribute(CommonUtil.ROLE_MAP);
		return new ModelAndView("redirect:/toLogin");
    }
	
	/**
	 * 无权限提示
	 * @author xudz
	 * @time 2017 2017年1月6日 上午9:56:26
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/noRight")
	public ModelAndView noRight(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("message", "无此操作权限");
		return new ModelAndView("exception");
	}
//	/**
//	 * AJAX接口获取当前用户可是以使用的菜单
//	 * 
//	 * @param request
//	 * @param response
//	 * @throws IOException
//	 */
//	@RequestMapping("/getMenu")
//	public void getMenu(HttpServletRequest request, HttpServletResponse response)
//			throws IOException {
//		SystemUserBase user = (SystemUserBase) request.getSession().getAttribute(CommonUtil.CURRENTUSER);
//		List<SystemRoleMenu> menuList = systemRoleMenuService.systemRoleMenuListByUser(user.getId());
//		String menuStr = LoginTool.getMenuString(menuList);
//		response.setCharacterEncoding("UTF-8");
//		response.setHeader("Content-type", "text/html;charset=UTF-8");
//		response.getWriter().print(menuStr);
//	}
	
	
	/**
	 * 跳转404
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 上午10:54:45
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/error404")
	public ModelAndView error404(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("message", "（404）请求地址不存在");
		return new ModelAndView("exception");
	}
	
	/**
	 * 跳转500
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 上午10:54:53
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/error500")
	public ModelAndView error500(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("message", "（500）程序异常");
		return new ModelAndView("exception");
	}
	
	/**
	 * 跳转503
	 *
	 * @author xudz
	 * @time 2017 2017年1月5日 上午10:54:31
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/error503")
	public ModelAndView error503(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("message", "（503）服务器崩溃");
		return new ModelAndView("exception");
	}
	
	/**
	 * 跳转到异常页
	 *
	 * @author 徐德志
	 * @time 2016 2016年4月21日 上午11:33:00
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exception")
	public ModelAndView exception(HttpServletRequest request,HttpServletResponse response){
		request.setAttribute("message", "程序异常");
		return new ModelAndView("exception");
	}
	
	/**
	 * 查询消息
	 *
	 * @author xudz
	 * @time 2017 2017年1月16日 下午3:34:21
	 * @parameter 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/acmessage")
	public void acmessage(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		SystemUserBase user=(SystemUserBase) session.getAttribute(CommonUtil.CURRENTUSER);
		//查询未阅读的消息数量
		Integer disreadCount= acMessageBaseService.disreadMessageCount(user);
		//查询已阅读的消息数量
		Integer readCount= acMessageBaseService.enreadMessageCount(user);
		//查询今日最新消息
//		Integer unreadToday=acMessageBaseService.unreadTodayMessage(user);
		
		JSONObject result=new JSONObject();
		result.accumulate("unreadCount", disreadCount);
		result.accumulate("readCount", readCount);
		
		writeResultMessage(response, result, SUCCESS);
		
	}
	
	/**
	 * 查询有效公告
	 *
	 * @author xudz
	 * @time 2017 2017年1月16日 下午3:34:30
	 * @parameter 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/notice")
	public void notice(HttpServletRequest request,HttpServletResponse response){
		JSONObject result=new JSONObject();
		
		ExtQueryBean extQuery=new ExtQueryBean();
		
		String appendSql=" AND now()>startTime AND now()<endTime ORDER BY id desc ";
		
		extQuery.setAppendSql(appendSql);
		
		AcNoticeBase condition=new AcNoticeBase();
		condition.setStatus(TldTool.STATUS_USE);
		
		Integer count=acNoticeBaseService.acNoticeBaseTotal(condition, extQuery);
		
		result.accumulate("count", count);

		if (count>0) {
			List<AcNoticeBase> notices=acNoticeBaseService.acNoticeBaseList(condition, extQuery);
			//条件查询有数量 肯定曼珠条件查询的结果大于0
			if(notices!=null&&notices.size()>0){
//				AcNoticeBase notice=notices.get(0);
				JSONArray jsonArr=new JSONArray();
				for (int i = 0; i < notices.size(); i++) {
					jsonArr.add(JSONObject.fromObject(notices.get(i)));
				}
				result.accumulate("notices", jsonArr);
			}
			
		}
		
		writeResultMessage(response, result, SUCCESS);
		
	}
	
	
	/**
	 * 查询已读消息列表
	 *
	 * @author 徐德志
	 * @time 2016 2016年5月24日 上午10:15:28
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/readList")
	public ModelAndView readList(HttpServletRequest request,HttpServletResponse response,ExtQueryBean extQuery) {
        if(extQuery.getPageNum() == null) {
            extQuery.setSize(10);
            extQuery.setPageNum(1);
        }
        
        extQuery.setAppendSql(" order by id desc ");
        
        HttpSession session = request.getSession();
		SystemUserBase user=(SystemUserBase) session.getAttribute(CommonUtil.CURRENTUSER);
		
		List<AcMessageBase> messageList=acMessageBaseService.enreadMessageList(user,extQuery);
		
		//查询已阅读的消息数量
		Integer readCount= acMessageBaseService.enreadMessageCount(user);
		extQuery.setTotal(readCount);
		
		request.setAttribute("messageList", messageList);
		
		request.setAttribute("type", 1);
		request.setAttribute("extQuery", extQuery);
		
		return new ModelAndView("admin/ac/messageList");
	}
	
	
	/**
	 * 查询未读消息列表
	 *
	 * @author 徐德志
	 * @time 2016 2016年5月24日 上午10:15:28
	 * @parameter 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/disreadList")
	public ModelAndView disreadList(HttpServletRequest request,HttpServletResponse response,ExtQueryBean extQuery) {
        if(extQuery.getPageNum() == null) {
            extQuery.setSize(10);
            extQuery.setPageNum(1);
        }
        
        extQuery.setAppendSql(" order by id desc ");
        
        HttpSession session = request.getSession();
		SystemUserBase user=(SystemUserBase) session.getAttribute(CommonUtil.CURRENTUSER);
		
		List<AcMessageBase> messageList=acMessageBaseService.disreadMessageList(user,extQuery);
		
		//查询未阅读的消息数量
		Integer disreadCount= acMessageBaseService.disreadMessageCount(user);
		extQuery.setTotal(disreadCount);
		
		request.setAttribute("messageList", messageList);
		
		request.setAttribute("type", 2);
		request.setAttribute("extQuery", extQuery);
		
		return new ModelAndView("admin/ac/messageList");
	}
	
	
	/**
	 * 添加阅读记录
	 *
	 * @author 徐德志
	 * @time 2016 2016年5月24日 下午2:03:54
	 * @parameter 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/addreadlog")
	public void addreadlog(HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
		SystemUserBase user=(SystemUserBase) session.getAttribute(CommonUtil.CURRENTUSER);
		Integer messageId=Integer.parseInt(request.getParameter("messageId"));
		
		AcMsgreadlogBase condition=new AcMsgreadlogBase();
		condition.setMessageId(messageId);
		condition.setUserId(user.getId());
		//查询当前用户 当前消息 是否存在阅读记录
		List<AcMsgreadlogBase> readlogList=acMsgreadlogBaseService.acMsgreadlogBaseList(condition, null);
		//不存在，添加操作
		if (readlogList==null||readlogList.size()==0) {
			AcMsgreadlogBase readlog=new AcMsgreadlogBase();
			
			readlog.setMessageId(messageId);
			readlog.setUserId(user.getId());
			readlog.setUserName(user.getUserName());
			readlog.setReadtime(new Date());
			acMsgreadlogBaseService.acMsgreadlogBaseInsert(readlog);
		}
		
		//存在不操作
		Map<String, String> result=new LinkedHashMap<String, String>();
		result.put("result", "ok");
		writeResultMessage(response,JSONObject.fromObject(result), SUCCESS);
	}
	
}
